import 'dart:convert';
import 'dart:math';

import 'package:base_pay/base_pay.dart';
import 'package:base_pay/entity/product/AndroidProductEntity.dart';
import 'package:base_pay/entity/product/IOSProductEntity.dart';
import 'package:base_pay/entity/product/IProductDetails.dart';
import 'package:base_pay/entity/purchase/AndroidPurchaseEntity.dart';
import 'package:base_pay/entity/purchase/IOSPurchaseEntity.dart';
import 'package:base_pay/entity/purchase/IPurchaseDetails.dart';
import 'package:base_pay/manager/BasePayManager.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:mybase/base/tool/empty/FFEmpty.dart';
import 'package:mybase/base/tool/entitylog/MyLog.dart';
import 'package:mybase/base/tool/extension/FFListExt.dart';
import 'package:mybase/base/tool/extension/FFMapExt.dart';
import 'package:mybase/base/tool/globalMethod/FFSafeValue.dart';
import 'package:mybase/base/tool/platformUtils/FFPlatform.dart';
import 'package:mybase/base/tool/pprint/FFLog.dart';
import 'base_pay_platform_interface.dart';
import 'package:in_app_purchase_android/in_app_purchase_android.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';

class MethodChannelBasePay extends BasePayPlatform {
  @visibleForTesting
  final methodChannel = const MethodChannel('base_pay');

  @override
  Future<String?> getPlatformVersion() async {
    final version = await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }

  List<IProductDetails>? _products;

  ///连接商店
  @override
  Future<bool> isAvailable() async {
    bool available = await InAppPurchase.instance.isAvailable();
    if (!available) {
      //debugPrint("base_pay:连接失败");
      return available;
    }

    //debugPrint("base_pay:连接成功");
    return available;
  }

  ///加载商品列表
  @override
  Future<List<IProductDetails>> queryProductDetails(
    Set<String> identifiers, {
    bool? priorityTrial,
    bool? getAll,
  }) async {
    ProductDetailsResponse response = await InAppPurchase.instance.queryProductDetails(identifiers);
    if (response.notFoundIDs.isNotEmpty) {
      FFLog.error("base_pay:未发现的identifiers = ${response.notFoundIDs.toString()}");
    }

    if (FFEmpty.listIsEmpty(response.productDetails)) {
      FFLog.error("base_pay:productDetails 为空");
      return [];
    }
    List<ProductDetails> oriProducts = response.productDetails;

    ///排序
    List<ProductDetails> products = [];
    identifiers.forEach((element) {
      oriProducts.forEach((oriElement) {
        if (element == oriElement.id) {
          products.add(oriElement);
        }
      });
    });

    List<IProductDetails> results = [];
    for (int i = 0; i < products.length; i++) {
      ProductDetails p = products[i];

      IProductDetails? iProductDetail;
      if (FFPlatform.isAndroid) {
        iProductDetail = AndroidProductEntity(details: p as GooglePlayProductDetails);
      } else {
        iProductDetail = IOSProductEntity(details: p as AppStoreProductDetails);
      }

      if (FFEmpty.stringIsEmpty(iProductDetail.getID())) {
        continue;
      }

      if (FFPlatform.isAndroid) {
        ///去重
        IProductDetails? existIProductDetail;
        results.forEach((element) {
          if (element.getID() == iProductDetail!.getID()) {
            existIProductDetail = element;
          }
        });

        if (existIProductDetail != null) {
          ///当有两个一样的时候
          if (priorityTrial == true) {
            ///优先返回试用产品
            bool existTry = existIProductDetail?.getFreeTry() ?? false;
            if (existTry != true) {
              AndroidProductEntity androidProductEntity = iProductDetail as AndroidProductEntity;
              ProductDetails rightProduct = existIProductDetail!.getProductDetails();
              androidProductEntity.currencyCode = rightProduct.currencyCode;
              androidProductEntity.price = rightProduct.price;
              androidProductEntity.rawPrice = rightProduct.rawPrice;
              androidProductEntity.currencySymbol = rightProduct.currencySymbol;

              int index = results.indexOf(existIProductDetail!);
              results.remove(existIProductDetail);
              results.insert(index, iProductDetail);
            } else {
              AndroidProductEntity androidProductEntity = existIProductDetail as AndroidProductEntity;
              ProductDetails rightProduct = iProductDetail.getProductDetails();
              androidProductEntity.currencyCode = rightProduct.currencyCode;
              androidProductEntity.price = rightProduct.price;
              androidProductEntity.rawPrice = rightProduct.rawPrice;
              androidProductEntity.currencySymbol = rightProduct.currencySymbol;
            }
          } else {
            ///优先返回没有试用的产品
            bool existTry = existIProductDetail?.getFreeTry() ?? false;
            if (existTry == true) {
              int index = results.indexOf(existIProductDetail!);
              results.remove(existIProductDetail);
              results.insert(index, iProductDetail);
            }
          }

          continue;
        }
      }

      results.add(iProductDetail);
    }

    _products = results;
    return results;
  }

  ///监听
  @override
  Future<void> listenToPurchaseUpdated(purchaseDetailsList) async {
    //debugPrint("base_pay: purchaseDetailsList length = ${purchaseDetailsList.length}");

    ///去重操作
    //把相同的transactionIdentifier放在一个组里面
    List<PurchaseDetails> allPurchaseDetailsList = [];

    if (FFPlatform.isIOS) {
      Map<String, PurchaseDetails> groupMap = {};
      for (int i = 0; i < purchaseDetailsList.length; i++) {
        PurchaseDetails purchaseDetails = purchaseDetailsList[i];

        if (!(purchaseDetails.status == PurchaseStatus.purchased ||
            purchaseDetails.status == PurchaseStatus.restored)) {
          allPurchaseDetailsList.add(purchaseDetails);
          continue;
        }

        if (purchaseDetails is AppStorePurchaseDetails) {
          AppStorePurchaseDetails iosPurchaseDetails = purchaseDetails;
          SKPaymentTransactionWrapper? originalTransaction =
              iosPurchaseDetails.skPaymentTransaction.originalTransaction;

          if (!FFEmpty.stringIsEmpty(originalTransaction?.transactionIdentifier)) {
            if (groupMap.containsKey(originalTransaction?.transactionIdentifier)) {
              //比较
              PurchaseDetails? mapPurchaseDetails = groupMap[originalTransaction!.transactionIdentifier!];
              if (mapPurchaseDetails == null) {
                groupMap[originalTransaction.transactionIdentifier!] = purchaseDetails;
              } else {
                int mapSecond = int.parse(mapPurchaseDetails.transactionDate ?? "0");
                int second = int.parse(purchaseDetails.transactionDate ?? "0");
                if (second > mapSecond) {
                  PurchaseDetails? old = groupMap[originalTransaction.transactionIdentifier!];
                  if (old != null) {
                    await _completePurchase(old);
                  }
                  groupMap[originalTransaction.transactionIdentifier!] = purchaseDetails;
                } else {
                  await _completePurchase(mapPurchaseDetails);
                }
              }
            } else {
              groupMap[originalTransaction!.transactionIdentifier!] = purchaseDetails;
            }
          } else {
            allPurchaseDetailsList.add(purchaseDetails);
          }
        }
      }
      List<PurchaseDetails> tistinctList = groupMap.values.toList();
      if (FFEmpty.listIsEmpty(tistinctList)) {
        //debugPrint("base_pay：去重后tistinctList.length: 0");
      } else {
        //debugPrint("base_pay：去重后tistinctList.length: ${tistinctList.length}");
        allPurchaseDetailsList.addAll(tistinctList);
      }
    } else {
      allPurchaseDetailsList.addAll(purchaseDetailsList);
    }

    if (!FFEmpty.listIsEmpty(allPurchaseDetailsList)) {
      //debugPrint("base_pay：处理后的订单列表.length: ${allPurchaseDetailsList.length}");
    } else {
      //debugPrint("base_pay：处理后的订单列表.length: 0");
      BasePayManager().delegate?.delegate_listenToEmptyPurchaseList();
    }

    List<IPurchaseDetails> restoredList = [];
    List<IPurchaseDetails> purchasedList = [];

    ///循环处理所有订单
    for (final PurchaseDetails purchaseDetails in allPurchaseDetailsList) {
      //debugPrint("base_pay: purchaseDetails status = ${purchaseDetails.status}");

      switch (purchaseDetails.status) {
        case PurchaseStatus.purchased:
          purchasedList.add(FFPlatform.isAndroid
              ? AndroidPurchaseEntity(details: purchaseDetails)
              : IOSPurchaseEntity(details: purchaseDetails));
          break;
        case PurchaseStatus.error:
          BasePayManager().delegate?.delegate_purchaseStatus_errord(FFPlatform.isAndroid
              ? AndroidPurchaseEntity(details: purchaseDetails)
              : IOSPurchaseEntity(details: purchaseDetails));
          await _completePurchase(purchaseDetails);
          break;
        case PurchaseStatus.canceled:
          BasePayManager().delegate?.delegate_purchaseStatus_canceled(FFPlatform.isAndroid
              ? AndroidPurchaseEntity(details: purchaseDetails)
              : IOSPurchaseEntity(details: purchaseDetails));
          await _completePurchase(purchaseDetails);
          break;
        case PurchaseStatus.pending:
          BasePayManager().delegate?.delegate_purchaseStatus_pending(FFPlatform.isAndroid
              ? AndroidPurchaseEntity(details: purchaseDetails)
              : IOSPurchaseEntity(details: purchaseDetails));
          break;
        case PurchaseStatus.restored:
          restoredList.add(FFPlatform.isAndroid
              ? AndroidPurchaseEntity(details: purchaseDetails)
              : IOSPurchaseEntity(details: purchaseDetails));
          break;
        default:
      }
    }

    if (!FFEmpty.listIsEmpty(purchasedList)) {
      BasePayManager().delegate?.delegate_purchaseStatus_purchased(purchasedList);
    }

    if (!FFEmpty.listIsEmpty(restoredList)) {
      BasePayManager().delegate?.delegate_purchaseStatus_restored(restoredList);
    } else {
      //TODO 提示没有恢复单
    }
  }

  ///完成订单
  @override
  completePurchase(IPurchaseDetails iPurchaseDetails) async {
    await _completePurchase(iPurchaseDetails.getDetail());
  }

  @override
  Future<String?> getiOSReceipt() async {
    final InAppPurchaseStoreKitPlatformAddition iosAddition =
        InAppPurchase.instance.getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
    try {
      PurchaseVerificationData? verificationData = await iosAddition.refreshPurchaseVerificationData();
      return verificationData?.serverVerificationData;
    } catch (e) {
      log_error("getiOSReceipt error ${e.toString()}");
      return null;
    }
  }

  ///查询历史订阅
  @override
  queryHistory({String? token}) async {
    if (FFPlatform.isAndroid) {
      ///android 历史
      final InAppPurchaseAndroidPlatformAddition androidAddition =
          InAppPurchase.instance.getPlatformAddition<InAppPurchaseAndroidPlatformAddition>();
      QueryPurchaseDetailsResponse? response = await androidAddition.queryPastPurchases(applicationUserName: token);
      //debugPrint("base_pay：queryPastPurchases = ${response.pastPurchases.length}");

      //如果拉取不到订单,
      if (FFEmpty.listIsEmpty(response.pastPurchases)) {
        BasePayManager().delegate?.delegate_noHistory();
        return;
      }

      List<IPurchaseDetails> pastList = [];
      for (int i = 0; i < response.pastPurchases.length; i++) {
        GooglePlayPurchaseDetails purchaseDetails = response.pastPurchases[i];
        if (purchaseDetails.status == PurchaseStatus.purchased) {
          if (purchaseDetails.billingClientPurchase.isAcknowledged) {
            pastList.add(AndroidPurchaseEntity(details: purchaseDetails));
          } else {
            _completePurchase(purchaseDetails);
          }
        }
      }

      if (FFEmpty.listIsEmpty(pastList)) {
        BasePayManager().delegate?.delegate_noHistory();
      } else {
        await BasePayManager().delegate?.delegate_androidHistoryPurchases(pastList);
      }
    } else {
      ///iOS 历史
      final InAppPurchaseStoreKitPlatformAddition iosAddition =
          InAppPurchase.instance.getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      PurchaseVerificationData? verificationData;
      try {
        verificationData = await iosAddition.refreshPurchaseVerificationData();
      } catch (e) {
        //debugPrint("base_pay 出错了 $e");
        BasePayManager().delegate?.delegate_queryHistoryError();

        return;
      }

      if (verificationData == null || FFEmpty.stringIsEmpty(verificationData.serverVerificationData)) {
        BasePayManager().delegate?.delegate_noHistory();
        return;
      }
      await BasePayManager().delegate?.delegate_iOSHistoryVerificationData(verificationData.serverVerificationData);
    }

    // 结束异常单
    _iosfinishTransaction();
  }

  ///发起订阅
  @override
  Future<bool> buyNonConsumable(IProductDetails iProductDetails, {String? token}) async {
    await _iosfinishTransaction();
    late PurchaseParam purchaseParam;
    if (FFPlatform.isAndroid) {
      purchaseParam = GooglePlayPurchaseParam(
        productDetails: iProductDetails.getProductDetails(),
        applicationUserName: token,
      );
    } else {
      purchaseParam = AppStorePurchaseParam(
        productDetails: iProductDetails.getProductDetails(),
        applicationUserName: token,
      );
    }

    return await InAppPurchase.instance.buyNonConsumable(purchaseParam: purchaseParam);
  }

  ///恢复购买
  @override
  restorePurchases({String? token}) async {
    await _iosfinishTransaction();
    await InAppPurchase.instance.restorePurchases(applicationUserName: token);
  }

  //完成订单
  _completePurchase(PurchaseDetails purchaseDetails) async {
    if (purchaseDetails.pendingCompletePurchase) {
      await InAppPurchase.instance.completePurchase(purchaseDetails);
    }

    // await InAppPurchase.instance.completePurchase(purchaseDetails);
  }

  //iOS结束异常订单事务
  _iosfinishTransaction() async {
    if (FFPlatform.isIOS) {
      try {
        var paymentWrapper = SKPaymentQueueWrapper();
        List<SKPaymentTransactionWrapper>? transactions = await paymentWrapper.transactions();
        if (!FFEmpty.listIsEmpty(transactions)) {
          for (SKPaymentTransactionWrapper transaction in transactions) {
            if (transaction.transactionState == SKPaymentTransactionStateWrapper.restored ||
                transaction.transactionState == SKPaymentTransactionStateWrapper.purchased ||
                transaction.transactionState == SKPaymentTransactionStateWrapper.failed) {
              paymentWrapper.finishTransaction(transaction);
            }
          }

          // 最多等待2秒
          int count = transactions.toLength;
          await Future.delayed(Duration(milliseconds: max(count, 20) * 100));
        }
      } catch (e) {
        FFLog.error("base_pay: iosfinishTransaction");
      }
    }
  }

  ///再次验证，走接口
  /**
   * 返回null：   代表出错了，
   * 返回空数组：  没有订阅
   * 返回[ids]:   订阅期内的商品id数组
   */
  @deprecated
  @override
  Future<List<String>?> verifyTheResultsAgain(
    VerifyAgainParam param, {
    int reTryNum = 1,
  }) async {
    if (reTryNum < 0) {
      return null;
    }

    List<String> ids = [];

    if (FFPlatform.isIOS) {
      var map = {
        "password": param.iosPassword,
        "receipt-data": param.iosReceiptData,
        "exclude-old-transactions": "true",
      };

      ///沙盒验证地址 https://sandbox.itunes.apple.com/verifyReceipt
      ///应用商店地址 https://buy.itunes.apple.com/verifyReceipt

      int connectTimeout = 45000;
      String appleurl = "https://buy.itunes.apple.com/verifyReceipt";
      var timeout = Duration(seconds: connectTimeout);
      Dio dio = Dio(BaseOptions(connectTimeout: timeout, receiveTimeout: timeout));
      var data = null;
      Map<String, dynamic>? result;
      try {
        FFLog.info("base_pay: 正在进行应用商店验证...");
        Response response = await dio.post(appleurl, data: map);
        data = response.data;
        if (data is String) {
          result = json.decode(data);
        } else {
          result = data as Map<String, dynamic>;
        }
      } catch (e) {
        FFLog.info("ios 应用商店请求出错了 $e");
        return await verifyTheResultsAgain(param, reTryNum: reTryNum - 1);
      }

      int? status21007 = globalSafeValueFromMap(result, "status");
      if (status21007 == 21007) {
        appleurl = "https://sandbox.itunes.apple.com/verifyReceipt";
        try {
          FFLog.info("base_pay: 正在进行沙盒验证...");
          Response response = await dio.post(appleurl, data: map);
          data = response.data;
          if (data is String) {
            result = json.decode(data);
          } else {
            result = data as Map<String, dynamic>;
          }
        } catch (e) {
          FFLog.info("ios 沙盒商店请求出错了 $e");
          return await verifyTheResultsAgain(param, reTryNum: reTryNum - 1);
        }
      }

      Mylog.p(url: appleurl, param: map, result: result);
      int? status = globalSafeValueFromMap(result, "status");
      //BasePayManager().delegate?.delegate_apiCode(status);

      if (!FFEmpty.mapIsEmpty(result)) {
        Map originalDataMap = result as Map;
        if (originalDataMap.safeValue<int>("status") == 0) {
          List? infos = originalDataMap.safeValue("latest_receipt_info");
          if (!FFEmpty.listIsEmpty(infos)) {
            for (int i = 0; i < infos!.length; i++) {
              Map purchaseInfo = infos[i];
              if (purchaseInfo.containsKey("expires_date_ms")) {
                String date_ms = purchaseInfo.safeValue<String>("expires_date_ms");
                if (!FFEmpty.stringIsEmpty(date_ms)) {
                  int expires_date_ms = int.parse(date_ms ?? "0");
                  int now_ms = param.millsecond ?? DateTime.now().millisecondsSinceEpoch;
                  if (now_ms <= expires_date_ms) {
                    /// 有效期内
                    if (!FFEmpty.stringIsEmpty(purchaseInfo.safeValue("product_id"))) {
                      ids.add(purchaseInfo.safeValue("product_id"));
                    }
                  }
                }
              } else {
                /// 永久购买
                if (!FFEmpty.stringIsEmpty(purchaseInfo.safeValue("product_id"))) {
                  ids.add(purchaseInfo.safeValue("product_id"));
                }
              }
            }
          }

          ///统计哪些组内的id之前订阅过
          List? inAppList = globalSafeValueFromMap<List>(originalDataMap, "latest_receipt_info");
          if (!FFEmpty.listIsEmpty(inAppList)) {
            //找出历史订单id集合
            Set<String> historyIDs = {};
            inAppList?.forEach((inAppMap) {
              String? productIdStr = globalSafeValueFromMap<String>(inAppMap, "product_id");
              if (!FFEmpty.stringIsEmpty(productIdStr)) {
                if (!historyIDs.contains(productIdStr!)) {
                  historyIDs.add(productIdStr);
                }
              }
            });

            //改变对象
            List<SubscribeGroup> groupList = BasePayManager().getSubscribeGroupList();
            for (var group in groupList) {
              group.didFreeTry = null;
              bool thisGroupHasHistory = false;
              for (var historyid in historyIDs) {
                if (thisGroupHasHistory) {
                  break;
                }
                if (group.ids.contains(historyid)) {
                  thisGroupHasHistory = true;
                }
              }

              if (thisGroupHasHistory) {
                group.didFreeTry = thisGroupHasHistory;
              }
            }
          }

          return ids;
        } else {
          return [];
        }
      }

      return null;
    }
  }

  ///再次验证，走接口
  /**
   * 返回null：   代表出错了，
   * 返回空数组：  没有订阅
   * 返回[ids]:   订阅期内的商品id数组
   */
  @override
  Future<List<PaySuccessInfo>?> verifyTheResultsAgain2(
    VerifyAgainParam param, {
    int reTryNum = 1,
  }) async {
    if (reTryNum < 0) {
      return null;
    }

    List<PaySuccessInfo> successInfo = [];

    if (FFPlatform.isIOS) {
      var map = {
        "password": param.iosPassword,
        "receipt-data": param.iosReceiptData,
        "exclude-old-transactions": "true",
      };

      ///沙盒验证地址 https://sandbox.itunes.apple.com/verifyReceipt
      ///应用商店地址 https://buy.itunes.apple.com/verifyReceipt

      int connectTimeout = 45000;
      String appleurl = "https://buy.itunes.apple.com/verifyReceipt";
      var timeout = Duration(seconds: connectTimeout);
      Dio dio = Dio(BaseOptions(connectTimeout: timeout, receiveTimeout: timeout));
      var data = null;
      Map<String, dynamic>? result;
      try {
        FFLog.info("base_pay: 正在进行应用商店验证...");
        Response response = await dio.post(appleurl, data: map);
        data = response.data;
        if (data is String) {
          result = json.decode(data);
        } else {
          result = data as Map<String, dynamic>;
        }
      } catch (e) {
        FFLog.info("ios 应用商店请求出错了 $e");
        return await verifyTheResultsAgain2(param, reTryNum: reTryNum - 1);
      }

      int? status21007 = globalSafeValueFromMap(result, "status");
      if (status21007 == 21007) {
        appleurl = "https://sandbox.itunes.apple.com/verifyReceipt";
        try {
          FFLog.info("base_pay: 正在进行沙盒验证...");
          Response response = await dio.post(appleurl, data: map);
          data = response.data;
          if (data is String) {
            result = json.decode(data);
          } else {
            result = data as Map<String, dynamic>;
          }
        } catch (e) {
          FFLog.info("ios 沙盒商店请求出错了 $e");
          return await verifyTheResultsAgain2(param, reTryNum: reTryNum - 1);
        }
      }

      Mylog.p(url: appleurl, param: map, result: result);
      int? status = globalSafeValueFromMap(result, "status");
      BasePayManager().delegate?.delegate_apiCode(status);

      if (!FFEmpty.mapIsEmpty(result)) {
        Map originalDataMap = result as Map;
        if (originalDataMap.safeValue<int>("status") == 0) {
          List? infos = originalDataMap.safeValue("latest_receipt_info");
          if (!FFEmpty.listIsEmpty(infos)) {
            for (int i = 0; i < infos!.length; i++) {
              Map purchaseInfo = infos[i];
              if (purchaseInfo.containsKey("expires_date_ms")) {
                String date_ms = purchaseInfo.safeValue<String>("expires_date_ms");
                if (!FFEmpty.stringIsEmpty(date_ms)) {
                  int expires_date_ms = int.parse(date_ms ?? "0");
                  int now_ms = param.millsecond ?? DateTime.now().millisecondsSinceEpoch;
                  if (now_ms <= expires_date_ms) {
                    //有效期内
                    if (!FFEmpty.stringIsEmpty(purchaseInfo.safeValue("product_id"))) {
                      String product_id = purchaseInfo.safeValue("product_id") ?? "";
                      String transaction_id = purchaseInfo.safeValue("transaction_id") ?? "";
                      successInfo.add(PaySuccessInfo(
                        productId: product_id,
                        transactionId: transaction_id,
                        isLifeTime: false,
                        expires_date_ms: expires_date_ms,
                      ));
                    }
                  }
                }
              } else {
                //永久购买
                if (!FFEmpty.stringIsEmpty(purchaseInfo.safeValue("product_id"))) {
                  String product_id = purchaseInfo.safeValue("product_id") ?? "";
                  String transaction_id = purchaseInfo.safeValue("transaction_id") ?? "";
                  successInfo.add(PaySuccessInfo(
                    productId: product_id,
                    transactionId: transaction_id,
                    isLifeTime: true,
                    expires_date_ms: 33303956400000, // 3025-05-12 19:00:00 有意思吧
                  ));
                }
              }
            }
          }

          ///统计哪些组内的id之前订阅过
          List? inAppList = globalSafeValueFromMap<List>(originalDataMap, "latest_receipt_info");
          if (!FFEmpty.listIsEmpty(inAppList)) {
            //找出历史订单id集合
            Set<String> historyIDs = {};
            inAppList?.forEach((inAppMap) {
              String? productIdStr = globalSafeValueFromMap<String>(inAppMap, "product_id");
              if (!FFEmpty.stringIsEmpty(productIdStr)) {
                if (!historyIDs.contains(productIdStr!)) {
                  historyIDs.add(productIdStr);
                }
              }
            });

            //改变对象
            List<SubscribeGroup> groupList = BasePayManager().getSubscribeGroupList();
            for (var group in groupList) {
              group.didFreeTry = null;
              bool thisGroupHasHistory = false;
              for (var historyid in historyIDs) {
                if (thisGroupHasHistory) {
                  break;
                }
                if (group.ids.contains(historyid)) {
                  thisGroupHasHistory = true;
                }
              }

              if (thisGroupHasHistory) {
                group.didFreeTry = thisGroupHasHistory;
              }
            }
          }

          return successInfo;
        } else {
          return [];
        }
      }

      return null;
    }
  }
}
